package cn.deepxi.org.service.impl;



import cn.deepxi.base.service.impl.BaseServiceImpl;
import cn.deepxi.org.domain.Department;
import cn.deepxi.org.mapper.DepartmentMapper;
import cn.deepxi.org.query.DeptQuery;
import cn.deepxi.org.service.IDepartmentService;
import cn.deepxi.utils.AjaxResult;
import cn.deepxi.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.java2d.pipe.AAShapePipe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
* @Description: TODO
* @Author: Mr.Pu
* @Version: 1.0
* @Date:  2022/4/19 18:52
*/
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public void add(Department department) {
        departmentMapper.add(department);
        String dirPath="";
        if(department.getParent_id()==null){
            dirPath="/"+department.getId();

        }else {
            Department byId = departmentMapper.findById(department.getParent_id());
            dirPath=byId.getDirPath()+"/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.upt(department);

    }


    @Override
    public void upt(Department department) {
        String dirPath="";
        if(department.getParent_id()==null){
            dirPath="/"+department.getId();

        }else {
            Department byId = departmentMapper.findById(department.getParent_id());
            if(department !=null){
                dirPath=byId.getDirPath()+"/"+department.getId();
            }


        }
        department.setDirPath(dirPath);
        departmentMapper.upt(department);
    }





    @Override
    public List<Department> findDeptTree() {

//        查找所有部门
        List<Department> depts = departmentMapper.findAll();
//
        List<Department> trees=new ArrayList<>();
//        把集合转为map解决时间复杂度问题
        Map<Long,Department> map=new HashMap<>();
        for (Department dept : depts) {
            map.put(dept.getId(),dept);
        }
        for (Department dept : depts) {
            if(dept.getParent_id()==null){
                trees.add(dept);
            }else {
//                得到父亲
                Department department = map.get(dept.getParent_id());
//                把儿子放入到父亲中
                department.getChildren().add(dept);
            }
        }
        return trees;
    }
}
